package schemup;

import java.io.File;

import obj.Table;

import org.json.JSONException;
import org.json.JSONObject;

import data.Db;
import data.ListTable;
import db.DBConnection;

import setting.DbConfig;
import setting.RunConfig;
import utils.FileUtils;

public class Schemup {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		System.out.println("Simple Schemup Start");
		parseParam(args);
		loadDatabaseConfig();
		createDatabaseConnection();
		loadTextSchema();

		System.out.println("Loaded tables: " + ListTable.tables.size());
		SchemupRunner.startSchemup();
		System.out.println("Done");

	}

	private static void parseParam(String[] args) {

		int current = 0;
		for (current = 0; current < args.length; current++) {
			String option = args[current].toLowerCase();
			if (option.equals("-config")) { // Config file
				String value = args[++current];
				RunConfig.dbConfigFile = value;

			}
		}

	}

	private static void loadDatabaseConfig() {
		String config = FileUtils.readFile(RunConfig.dbConfigFile);

		try {
			JSONObject json = new JSONObject(config);

			String dbtype = json.getString("dbtype");
			String host = json.getString("host");
			int port = json.getInt("port");
			String dbname = json.getString("dbname");
			String dbuser = json.getString("dbuser");
			String dbpass = json.getString("dbpass");

			DbConfig.dbType = dbtype;
			DbConfig.host = host;
			DbConfig.port = port;
			DbConfig.database = dbname;
			DbConfig.username = dbuser;
			DbConfig.password = dbpass;

			System.out.println("Config loaded");

		} catch (JSONException e) {
			System.out.println("Error: " + e.getMessage());
			System.exit(-1);
		}

	}

	private static void createDatabaseConnection() {
		Db.db = new DBConnection();
	}

	private static void loadTextSchema() {
		File folder = new File(RunConfig.schemaDirectory);
		if (!folder.exists() || !folder.isDirectory()) {
			System.out.println("Error:Directory <" + RunConfig.schemaDirectory
					+ "> does not exist");
			System.exit(-1);

		}

		File[] listOfFiles = folder.listFiles();
		for (int i = 0; i < listOfFiles.length; i++) {
			File file = listOfFiles[i];
			if (file.isFile() && file.getName().endsWith(".sch")
					&& !file.getName().equals("test.sch")) {
				String fileContent = FileUtils.readFile(file.getAbsolutePath());
				ListTable.addTable(new Table(file.getName(), fileContent));
			}
		}

	}
}
